package com.leyou.page.service;

import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    public Map<String, Object> loadItemData(Long spuId) {
        // 1.查询数据
        // 1.1.查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 1.2.查询分类
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 1.3.查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        // 1.4.查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecListByCid(spu.getCid3());
        // 组织数据
        Map<String, Object> data = new HashMap<>();
        data.put("categories", categories);
        data.put("brand", brand);
        data.put("spuName", spu.getName());
        data.put("subTitle", spu.getSubTitle());
        data.put("detail", spu.getSpuDetail());
        data.put("skus", spu.getSkus());
        data.put("specs", specs);
        return data;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    private static final String ITEM_TEMPLATE_NAME = "item";
    private static final String ITEM_HTML_DIR = "C:\\lesson\\heima87\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long spuId) {
        // 准备上下文
        Context context = new Context();
        // 准备数据
        context.setVariables(loadItemData(spuId));

        // 准备目标文件
        File file = new File(ITEM_HTML_DIR, spuId + ".html");
        // 准备输出流，关联目标文件
        try (Writer writer = new PrintWriter(file, "UTF-8")) {
            // 渲染页面，写到指定文档
            templateEngine.process(ITEM_TEMPLATE_NAME, context, writer);
        } catch (Exception e) {
            throw new RuntimeException("文件写出失败！", e);
        }
    }

    public void deleteItemHtml(Long spuId) {
        File file = new File(ITEM_HTML_DIR, spuId + ".html");
        if(file.exists()){
            boolean isDelete = file.delete();
            if(!isDelete){
                throw new RuntimeException("删除文件失败！");
            }
        }
    }
}
